package com.shujia.flink.window

import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows
import org.apache.flink.streaming.api.windowing.time.Time

object Demo2SessionWindow {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val kvDS: DataStream[(String, Int)] = linesDS.flatMap(_.split(",")).map((_, 1))

    /**
     * 会话窗口：一段时间没有数据再对前面接收到的数据进行计算
     * ProcessingTimeSessionWindows: 处理时间的会话窗口
     * EventTimeSessionWindows： 事件时间的会话窗口
     */
    val countDS: DataStream[(String, Int)] = kvDS
      .keyBy(_._1)
      .window(ProcessingTimeSessionWindows.withGap(Time.seconds(10)))
      .sum(1)

    countDS.print()

    env.execute()
  }

}
